<?php

namespace App\HttpController\V1;


use App\Common\Checking;
use App\Common\Sms;
use App\Tools\Token\Token;
use EasySwoole\EasySwoole\Config;
use EasySwoole\Validate\Validate;

class Login extends BaseWithDb
{
    public $user;

    function demo()
    {
//        $ip=$this->request()->getHeaders()['real-ip']??'获取失败';
        $table_name = '`users_position` as p';
        $team_num = $this->db
            ->join('`users` as u','p.user_id = u.id')
            ->where('p.pid',1)
            ->where('u.is_pay',2)
            ->count($table_name);
        return $this->writeJson( -4, $team_num, '请填写推荐码' );
    }

    /**
     * 执行注册
     * @return bool
     */
    function doRegister()
    {
        $param = $this->input();
        $validate = new Validate();

        $validate->addColumn( 'phone', '^1+[3456789]+\\d{9}' )->required( '手机号格式有误' );
        $validate->addColumn( 'password', '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$' )->required( '密码格式有误' )->betweenLen( 6, 18, '密码长度在6~18之间' );

//        if ( !isset( $param['inviteCode'] ) ) {
//            return $this->writeJson( -4, null, '请填写推荐码' );
//        }

        if ( !$this->validate( $validate ) ) {
            return $this->writeJson( -200, null, $validate->getError()->__toString() );
        }

        if ( $param['password'] != $param['re_password'] ) {
            return $this->writeJson( -3, null, '两次输入密码不一致' );
        }
        $model = $this->db;
        $tableName = 'users';
        $pid = 0;
        $times = date( 'YmdHis' );
        #判断注册账号是否存在
        if ( $model->where( 'mobile', $param['phone'] )->getOne( $tableName, 'id' ) > 0 ) {
            return $this->writeJson( -3, null, '用户已存在' );
        }
        if (isset($param['inviteCode']) && $param['inviteCode'] !=''){
            $fatherId = $model
                ->where( 'uuid', $param['inviteCode'] )
                ->getOne( $tableName, 'id' );
            if (empty($fatherId)){
                return $this->writeJson( -3, null, '上级不存在' );
            }
            $pid = $fatherId['id'];
        }else{
            return $this->writeJson( -3, null, '请填写上级邀请码' );
        }
//        return $this->writeJson( -3, 12, '' );
        $codes = Checking::nonceStrByUnique( 'uuid', $model, $tableName, 6, 2 );

        $validateArr = $validate->getVerifiedData();
        $insert = [
            'pid' => $pid,
            'uuid' => $codes,
            'nickname' => (isset($param['nickname']))?$param['nickname']:'默认昵称',
            'mobile' => $validateArr['phone'],
            'password' => Checking::passwordHash( $validateArr['password'] ),
            'createtime' => $times
        ];

        $model->startTransaction();
        #判断验证码和手机号
        $smsModel = new Sms();
        $sms = $smsModel->confirmation( $param['phone'], $param['code'], 1, $model );
        try {
            if ( $sms['status'] != 1 ) {
                throw new \Exception( $sms['msg'], -5 );
            }
            $newId = $model->insert( $tableName, $insert );
//            $model->insert( 'users_asset', ['user_id' => $newId] );
            if ( $newId && $pid > 0 ) {
                $position = $model
                    ->where( 'user_id', $pid )
                    ->get( 'users_position', null, '*' );
                $action = [];
                #推荐人等级
                $pid_user_info=$this->db->where('id',$pid)->getOne('users');
                if ( $position ) {
                    $action[0]['user_id'] = $newId;
                    $action[0]['pid'] = $pid;
                    $action[0]['lay'] = 1;
//                    $action[0]['level'] = $pid_user_info['level'];
//                    $action[0]['is_pay'] = $pid_user_info['is_pay'];
//                    $action[0]['status'] = $pid_user_info['status'];
                    $action[0]['create_time'] = $insert['createtime'];
                    foreach ( $position as $k => $v ) {
                        $action[ $k + 1 ]['user_id'] = $newId;
                        $action[ $k + 1 ]['pid'] = $v['pid'];
                        $action[ $k + 1 ]['lay'] = $v['lay'] + 1;
//                        $action[ $k + 1 ]['level'] = $v['lay'];
//                        $action[ $k + 1 ]['is_pay'] = $v['is_pay'];
//                        $action[ $k + 1 ]['status'] = $v['status'];
                        $action[ $k + 1 ]['create_time'] = $insert['createtime'];
                    }
                    $model->insertMulti( 'users_position', $action );
                } else {
                    $action['user_id'] = $newId;
                    $action['pid'] = $pid;
                    $action['lay'] = 1;
//                    $action['level'] = $pid_user_info['level'];
//                    $action['is_pay'] = $pid_user_info['is_pay'];
//                    $action['status'] = $pid_user_info['status'];
                    $action['create_time'] = $insert['createtime'];
                    $model->insert( 'users_position', $action );
                }
            }
            #注册成功送3天会员
            $send_vip=$this->db->where('name','send_vip')->getValue('config','value');
            $vip_time=time()+86400*$send_vip;
            $vip=date('Y-m-d H:i:s',$vip_time);
            $this->db->where('id',$newId)->update('users',['vip_expire_time'=>$vip,'level'=>4]);
            $model->commit();
            return $this->writeJson( 200, null, '注册成功' );
        } catch ( \Exception $e ) {
            $model->rollback();
            return $this->writeJson( $e->getCode(), null, $e->getMessage() );
        }
    }
    public function login_config(){
        $send_vip=$this->db->where('name','send_vip')->getValue('config','value');
        return $this->writeJson( 200, $send_vip, 'ok' );
    }
    /**
     * 登录
     */
    function doLogin()
    {
        $param = $this->input();
        if ( !Checking::keyIsExistence( ['phone', 'password'], $param ) ) {
            return $this->writeJson( -1, null, Checking::MESSAGE['keyIsExistence'] );
        }

        if ( !Checking::passwordRule( $param['password'] ) ) {
            return $this->writeJson( -1, null, Checking::MESSAGE['passwordRule'] );
        }

        $model = $this->db;
        $users = $model->where( 'mobile', $param['phone'] )->getOne( 'users', '*' );

        if ( !$users ) {
            return $this->writeJson( -1, null, '账号或密码错误' );
        }

        if ( !Checking::checkPassword( $users['password'], $param['password'] ) ) {
            return $this->writeJson( -1, null, Checking::MESSAGE['checkPassword'] );
        }
        if ( $users['status'] == 4 ) {
            return $this->writeJson( -3, null, '账户被封禁,请联系客服' );
        }
        $data = [
            'id' => $users['id'],
            'uuid' => $users['uuid'],
            'mobile' => $users['mobile'],
            'nickname' => $users['nickname'],
            'headimg' => $users['headimg'],
            'token' => md5( time() . mt_rand( 1000, 9999 ) )
        ];
        $exprie = 24 * 60 * 60 * 7;
//        $exprie = 5;
        $isOk= $this->redis->setex( 'jwtToken' . $data['id'], $exprie, $data['token'] );//请求接口时验证jwtToken是否相同,不相同则为错误
        $jwt = Token::encode( $data, $exprie );
        #登录次数
        $this->db->where('id',$users['id'])->setInc('users','first_log',1);
        $this->db->where('id',$users['id'])->setInc('users','day_log',1);
//        $this->response()->setCookie( Config::getInstance()->getConf( 'TOKEN_NAME' ), $jwt, null, '/', '', false, false );
//        $this->response()->withHeader(Config::getInstance()->getConf( 'TOKEN_NAME' ),$jwt);
        $this->writeJson( 200, ['code' => $jwt,'uuid'=>$users['uuid'],'uid'=>$users['id']], '登录成功' );

    }

    function loginOut()
    {
//        $this->response()->setCookie( Config::getInstance()->getConf( 'TOKEN_NAME' ), null, -1, '/', '', false, true );
        $this->writeJson( 200, null, '退出成功' );
    }

    public function bindwx(){
//        wx_openid
        $input=$this->input();
        if (!Checking::keyIsExistence('openId,phone',$input)){
            $this->writeJson(201,null,Checking::MESSAGE['keyIsExistence']);
        }
        $data['wx_openid']=$input['openId'];
        $this->db->where('mobile',$input['phone'])->update('users', $data);

        $this->writeJson(200,null,'绑定成功');
    }

    public function wxlogin(){
        $input=$this->input();
        if (!Checking::keyIsExistence('openId',$input)){
            $this->writeJson(201,null,Checking::MESSAGE['keyIsExistence']);
        }
        $model = $this->db;
        $users = $model->where( 'wx_openid', $input['openId'] )->getOne( 'users', '*' );

        if ( !$users ) {
            return $this->writeJson( -1, null, '未绑定账号' );
        }

        if ( $users['status'] == 4 ) {
            return $this->writeJson( -3, null, '账户被封禁,请联系客服' );
        }
        $data = [
            'id' => $users['id'],
            'uuid' => $users['uuid'],
            'mobile' => $users['mobile'],
            'nickname' => $users['nickname'],
            'headimg' => $users['headimg'],
            'token' => md5( time() . mt_rand( 1000, 9999 ) )
        ];
        $exprie = 24 * 60 * 60 * 7;
//        $exprie = 5;
        $isOk= $this->redis->setex( 'jwtToken' . $data['id'], $exprie, $data['token'] );//请求接口时验证jwtToken是否相同,不相同则为错误
        $jwt = Token::encode( $data, $exprie );
        #登录次数
        $this->db->where('id',$users['id'])->setInc('users','first_log',1);
        $this->db->where('id',$users['id'])->setInc('users','day_log',1);
        $this->writeJson( 200, ['code' => $jwt,'uuid'=>$users['uuid'],'uid'=>$users['id']], '登录成功' );

    }
    /**
     * 忘记密码
     * @param $phone
     * @param $code
     * @param $password
     * @param $repassword
     */
    public function forgetLoginPwd()
    {
        $param = $this->input();
        try {
            if ( !Checking::keyIsExistence( 'phone,code,password,repassword', $param ) ) {
                throw new \Exception( Checking::MESSAGE['keyIsExistence'], -1 );
            }
            if ( !Checking::phoneIsMysql( $param['phone'], 'users', $this->db, 'mobile' ) ) {
                throw new \Exception( '此手机号尚未注册', -2 );
            }
            if ( !Checking::passwordRule( $param['password'] ) ) {
                throw new \Exception( Checking::MESSAGE['passwordRule'], -4 );
            }
            #再次确认密码
            if ( $param['password'] != $param['repassword'] ) {
                throw new \Exception( '两次输入密码不一致', -4 );
            }
            #判断验证码和手机号
            $smsModel = new Sms();
            $sms = $smsModel->confirmation( $param['phone'], $param['code'], 6, $this->db );
            if ( $sms['status'] != 1 ) {
                throw new \Exception( '验证码错误', -5 );
            }
            $data = [];
            $data['password'] = Checking::passwordHash( $param['password'] );
            $data['updatetime'] = date( 'YmdHis' );
            #修改用户密码插入表中
            $result = $this->db->where( 'mobile', $param['phone'] )->update( 'users', $data );
            if ( $result ) {
                throw new \Exception( '修改成功', 200 );
            }
            throw new \Exception( '修改失败', -200 );
        } catch ( \Exception $e ) {
            $this->writeJson( $e->getCode(), null, $e->getMessage() );
        }
    }

    /**
     * 发送验证码
     * @param string $phone 手机号
     * @param int $type (1注册，2设置二级密码,3修改二级密码,4修改登录密码,6忘记密码,7绑定微信,8绑定支付宝,9=绑定银行卡)
     */
    public function getSmsCode()
    {
        $params = $this->input();
        try {

            if ( !Checking::keyIsExistence( 'type', $params ) ) {
                throw new \Exception( Checking::MESSAGE['keyIsExistence'], -1 );
            }
            #注册
            if ( $params['type'] == 1 ) {   //注册
                $phone = $params['phone'];
                if ( empty( $phone ) ) {
                    throw new \Exception( '手机号不准为空', -2 );
                }
                if ( Checking::phoneIsMysql( $phone, 'users', $this->db, 'mobile' ) ) {
                    throw new \Exception( Checking::MESSAGE['phoneIsMysql'], -2 );
                }
            } else if ( $params['type'] == 6 ) {    //忘记密码
                $phone = $params['phone'];
                if ( empty( $phone ) ) {
                    throw new \Exception( '手机号不准为空', -2 );
                }
                if ( !Checking::phoneIsMysql( $phone, 'users', $this->db, 'mobile' ) ) {
                    throw new \Exception( '此手机号尚未注册', -3 );
                }
            } else {
                $jwt = $this->request()->getHeader( Config::getInstance()->getConf( 'TOKEN_NAME' ) );
                if ( empty( $jwt ) ) {
                    throw new \Exception( '请先登录' );
                }
                $data = Token::decode( $jwt[0] );
                $this->user=$data['content'];
                if ( $data['status'] == false ) {
                    throw new \Exception( '用户信息不匹配,请退出重新登录', -6 );
                }
                $phone = $this->user->phone;

                $uid = $this->user->id;
            }

            if ( in_array( $params['type'], [2, 3, 4, 7, 8, 9] ) ) {
                if ( !$uid ) {
                    throw new \Exception( '用户信息失效，请重新登录', -3 );
                }

                if ( !$this->db->where( 'id', $uid )->getOne( 'users', 'id' ) ) {
                    throw new \Exception( '用户信息失效，请重新登录', -4 );
                }
            }
            $result = ( new Sms() )->reg_send( $phone, $params['type'], $this->db );

            if ( $result['status'] !== -1 && $result['status'] != -2 ) {
                throw new \Exception( '发送成功', 200 );
            } else if ( $result['status'] == -2 ) {

                throw new \Exception( '上次验证码还未失效!', -5 );
            } else {
                throw new \Exception( '短信平台出错,发送失败!', -6 );
            }
        } catch ( \Exception $e ) {
            $this->writeJson( $e->getCode(), null, $e->getMessage() );
        }
    }


}